{% extends 'base.html' %}

{% block javascript %}
<script>

  var platform = "unknown"
  
  window.onload = function() {
    getInfoAndUpdateView()
  }

  function getInfoAndUpdateView() {
    console.log("Getting info and updating view")
    document.getElementById("status").innerHTML = "Loading network status..."

    // Initialize info vars
    var systemInfo = {};
    var networkInfo = {};
    var iotInfo = {};

    // Get system info
    getSystemInfo()
      .then(function(systemInfo) {
        var systemInfo = systemInfo;
        platform = systemInfo["platform"];
        
        // Get network info
        getNetworkInfo()
          .then(function(networkInfo) {
            var networkInfo = networkInfo;

            // Get iot info
            getIotInfo()
              .then(function(iotInfo) {
                var iotInfo = iotInfo;

                // Update view
                updateView(systemInfo, networkInfo, iotInfo)
              })
          })
      })
      .catch(function(error) {
        console.log("Error: " + error);
      })
  }

  function updateView(systemInfo, networkInfo, iotInfo) {
    console.log("Updating view");
    console.log(systemInfo)
    console.log(networkInfo)
    console.log(iotInfo)

    // Update view for connected network and connected iot
    if (networkInfo["isConnected"] && iotInfo["isConnected"]) {
      document.getElementById("status").innerHTML = "Successfully connected!"
      document.getElementById("ip-address").innerHTML = networkInfo["ipAddress"];
      document.getElementById("remote-device-ui-url").innerHTML = systemInfo["remoteDeviceUiUrl"];
      document.getElementById("remote-device-ui-url").href = systemInfo["remoteDeviceUiUrl"];
      document.getElementById("cloud-ui-url").innerHTML = "https://openag-v1.appspot.com/login/";
      document.getElementById("cloud-ui-url").href = "https://openag-v1.appspot.com/login/";
      $('#connection-info-collapse').collapse("show");
      $('#configure-wifi-collapse').collapse("hide");
      $("#additional-network-message-collapse").collapse("hide");
      $("#registration-complete-collapse").collapse("hide");
    }

    // Update view for connected network and unconnected iot
    else if (networkInfo["isConnected"] && !iotInfo["isConnected"]) {
      document.getElementById("status").innerHTML = "Connected to network, disconnected from iot"
      document.getElementById("ip-address").innerHTML = networkInfo["ipAddress"];
      document.getElementById("remote-device-ui-url").innerHTML = systemInfo["remoteDeviceUiUrl"];
      document.getElementById("remote-device-ui-url").href = systemInfo["remoteDeviceUiUrl"];
      document.getElementById("cloud-ui-url").innerHTML = "Please click here to create your user account, and connect your PFC to the OpenAg Cloud";
      document.getElementById("cloud-ui-url").href = "https://openag-v1.appspot.com/login?vcode=" + iotInfo["verificationCode"];
      $('#connection-info-collapse').collapse("show");
      $('#configure-wifi-collapse').collapse("hide");
      $("#additional-network-message-collapse").collapse("hide");
      $("#registration-complete-collapse").collapse("hide");
    }

    // Update view for disconnected network and non-wifi-enabled system
    else if (!networkInfo["isConnected"] && !systemInfo["isWifiEnabled"]) {
        document.getElementById("status").innerHTML = "Unable to connect, platform is not wifi-enabled"
        $("#configure-wifi-collapse").collapse("hide");
        $("#connection-info-collapse").collapse("hide");
        $("#additional-network-message-collapse").collapse("hide");
    }

    // Update view for disconnected network and wifi-enabled system and registered iot
    else if (!networkInfo["isConnected"] && systemInfo["isWifiEnabled"] && iotInfo["isRegistered"]) {
      if (systemInfo["platform"] == "raspberry-pi-3") {
        document.getElementById("status").innerHTML = "Please register your device to your cloud user account. To do so, copy the web ui link, disconnect your laptop from the device access point then reconnect your laptop to an active network and paste in the web ui link. Once your device is registered to your cloud account, reconnect to the device access point and press the `Registration Complete` button below."
        document.getElementById("ip-address").innerHTML = "N/A";
        document.getElementById("cloud-ui-url").innerHTML = "https://openag-v1.appspot.com/login?vcode=" + iotInfo["verificationCode"];
        document.getElementById("cloud-ui-url").href = "https://openag-v1.appspot.com/login?vcode=" + iotInfo["verificationCode"];
        document.getElementById("remote-device-ui-url").innerHTML = systemInfo["remoteDeviceUiUrl"];
        document.getElementById("remote-device-ui-url").href = systemInfo["remoteDeviceUiUrl"];
        $("#connection-info-collapse").collapse("show");
        $("#additional-network-message-collapse").collapse("show");
        $("#registration-complete-collapse").collapse("show");
      }
      else {
        document.getElementById("status").innerHTML = "Please configure your wifi network"
      }

      updateWifiSSIDs(networkInfo["wifiSSIDs"]);

      // Check wifi networks have loaded
      var wifiSelect = document.getElementById("wifi-ssids-select");
      if (wifiSelect != null && wifiSelect.options.length < 1) {
        document.getElementById("status").innerHTML = "Please wait for network connections to load...refresh page in a few moments";
      }

      $("#configure-wifi-collapse").collapse("show");
    }

    // Update view for disconnected network and wifi-enabled system and unregistered iot
    else if (!networkInfo["isConnected"] && systemInfo["isWifiEnabled"] && !iotInfo["isRegistered"]) {
      document.getElementById("status").innerHTML = "Please configure your wifi network"
      updateWifiSSIDs(networkInfo["wifiSSIDs"]);

      // Check wifi networks have loaded
      var wifiSelect = document.getElementById("wifi-ssids-select");
      if (wifiSelect != null && wifiSelect.options.length < 1) {
        document.getElementById("status").innerHTML = "Please wait for network connections to load...refresh page in a few moments";
      }

      $("#network-info-collapse").collapse("hide");
      $("#configure-wifi-collapse").collapse("show");
      $("#additional-network-message-collapse").collapse("hide");
      $("#registration-complete-collapse").collapse("hide");
    }

  }


  function getSystemInfo() {
    console.log("Getting system info")
    return new Promise(function (resolve, reject) {
      $.ajax({
        url: "/api/system/info/",
        type: "GET",
        data: {
          "csrfmiddlewaretoken": "{{ csrf_token }}"
        },
        dataType: 'json',
        success: function(data) {
          console.log("Got system info")
          var systemInfo = {
            "platform": data["platform"],
            "serialNumber": data["serial_number"],
            "remoteDeviceUiUrl": data["remote_device_ui_url"],
            "isWifiEnabled": data["is_wifi_enabled"]
          };
          resolve(systemInfo);
        },
        error: function(data) {
          response_dict = JSON.parse(data.responseText);
          message = response_dict["message"];
          console.log(message);
          var systemInfo = {};
          reject(systemInfo);
        }
      });
    });
  }

  function updateWifiSSIDs(wifiSSIDs) {
    console.log("Updating wifi ssids")
    console.log(wifiSSIDs)

    // Get wifi ssids select
    var wifiSSIDSelect = document.getElementById("wifi-ssids-select");

    // Remove stale wifi ssid selections
    if (wifiSSIDSelect != null) {
      for( i=wifiSSIDSelect.length - 1; i >= 0; i-- ) { // must do in reverse
        wifiSSIDSelect.remove(i);
      } 
    }

    // Add updated wifi ssid selections
    if (wifiSSIDs != null) {
      for( i=0; i < wifiSSIDs.length; i++ ) {
        wifiSSID = wifiSSIDs[i];
        var option = document.createElement("option");
        option.text = wifiSSID;
        option.value = wifiSSID;
        wifiSSIDSelect.add(option);
      }
    }
  }

  function getNetworkInfo() {
    console.log("Getting network info")
    return new Promise(function (resolve, reject) {
      $.ajax({
        url: "/api/network/info/",
        type: "GET",
        data: {
          "csrfmiddlewaretoken": "{{ csrf_token }}"
        },
        dataType: 'json',
        success: function(data) {
          console.log("Got network info")
          var networkInfo = {
            "isConnected": data["is_connected"],
            "ipAddress": data["ip_address"],
            "wifiSSIDs": data["wifi_ssids"]
          }
          console.log(networkInfo);
          resolve(networkInfo);
        },
        error: function(data) {
          console.log("Unable to get network info")
          response_dict = JSON.parse(data.responseText)
          message = response_dict["message"]
          console.log(message);
          var networkInfo = {};
          reject(networkInfo);
        }
      });
    });
  }

  function getIotInfo() {
    console.log("Getting iot info")
    return new Promise(function (resolve, reject) {
      $.ajax({
        url: "/api/iot/info/",
        type: "GET",
        data: {
          "csrfmiddlewaretoken": "{{ csrf_token }}"
        },
        dataType: 'json',
        success: function(data) {
          console.log("Got system info")
          var iotInfo = {
            "isRegistered": data["is_registered"],
            "isConnected": data["is_connected"],
            "verificationCode": data["verification_code"]
          };
          resolve(iotInfo);
        },
        error: function(data) {
          response_dict = JSON.parse(data.responseText);
          message = response_dict["message"];
          console.log(message);
          var iotInfo = {};
          reject(iotInfo);
        }
      });
    });
  }

  function joinWifi() {
    console.log("Joining wifi")
    
    // Update status and processing view
    console.log(platform);
    if (platform == "raspberry-pi-3") {
      document.getElementById("status").innerHTML = "Joining wifi, this will take a few minutes...please wait for the device to reboot then reconnect your laptop to the device access point to finish setup."
    }
    else {
      document.getElementById("status").innerHTML = "Joining wifi, this will take a few minutes..."
    }
    $('#configure-wifi-collapse').collapse("hide");


    // Get wifi ssid
    var wifiSelect = document.getElementById("wifi-ssids-select");
    var wifiSSID = wifiSelect.options[wifiSelect.selectedIndex];
    if( wifiSSID == null ) {
      console.log("Error: could not get wifiSSIDs element");
      return;
    }

    // Get wifi password
    var wifiPassword = document.getElementById("wifi-password");
    if( wifiPassword == null ) {
      console.log("Error: could not get wifi-password element");
      return;
    }

    // Send join wifi request
    console.log("Sending join wifi request");
    $.ajax({
      url: "/api/network/joinwifi/",
      type: "POST",
      data: {
        "csrfmiddlewaretoken": "{{ csrf_token }}",
        "wifi_ssid": wifiSSID.value,
        "wifi_password": wifiPassword.value
      },
      dataType: 'json',
      success: function(data) {
        console.log("Successfully joined wifi");
        getInfoAndUpdateView();
      },
      error: function(data) {
        console.log("Unable to join wifi");
        response_dict = JSON.parse(data.responseText);
        message = response_dict["message"];
        console.log(message);
        console.log(response_dict);
        getInfoAndUpdateView();
      }
    });
  }

  function disableRaspiAccessPoint() {
    console.log("Disabling raspberry pi access point")
    
    // Update status and processing view
    document.getElementById("status").innerHTML = "Completing registration...please use cloud ui for all further interactions."
    $('#configure-wifi-collapse').collapse("hide");
    $("#connection-info-collapse").collapse("hide");
    $("#additional-network-message-collapse").collapse("hide");
    $("#registration-complete-collapse").collapse("hide");

    // Send join wifi request
    console.log("Sending join wifi request");
    $.ajax({
      url: "/api/network/disableraspiaccesspoint/",
      type: "POST",
      data: {
        "csrfmiddlewaretoken": "{{ csrf_token }}",
      },
      dataType: 'json',
      success: function(data) {
        console.log("Successfully disabled raspberry pi access point");
        getInfoAndUpdateView();
      },
      error: function(data) {
        console.log("Failed to disable raspberry pi access point");
        response_dict = JSON.parse(data.responseText);
        message = response_dict["message"];
        console.log(message);
        console.log(response_dict);
        getInfoAndUpdateView();
      }
    });
  }

  function makePasswordVisible() {
    var pass = document.getElementById("wifi-password");
    if (pass.type === "password") {
        pass.type = "text";
    } else {
        pass.type = "password";
    }
  }

</script>
{% endblock %}


{% block content %}

{% csrf_token %}

<html>

<input type="hidden" id="wifi-ssids" name="variable", value="temp">

<body>

<div class="connect">
  
  <h2>Connect</h2>
  <div class="card" id="connect-card">
    
    <h3>Networking</h3></br>

    <p>
      <b>Status:</b> <span id="status"></span>
    </p>

    <div class="collapse" id="connection-info-collapse">
      <ul>
        <li><b>Device IP Address:</b> <span id="ip-address"></span>
        <li><b>Web UI:</b> <a id="cloud-ui-url" href="https://openag-v1.appspot.com/login" target="_blank">OpenAg Web UI</a>
        <li><b>Remotely Accessible Device UI:</b> <a id="remote-device-ui-url" href="" target="_blank"></a>
      </ul>
    </div>

    <div class="collapse" id="registration-complete-collapse">
      <p></br>
        Cloud registration complete?
        
        <a class="badge badge-secondary" data-toggle="collapse" id="join-wifi-button"
        style="width:200px" href="" role="button" onclick="disableRaspiAccessPoint();">
        Registration Complete </a>

      </p>
    </div>
    

    <div class="collapse" id="additional-network-message-collapse">
      <p></br>
        <b>Optional:</b> If you have already connected to a wifi network, please disregard this. However, if you would like to connect to a new wifi network please enter the information below.
      </p>
    </div>
    
    <div class="collapse" id="configure-wifi-collapse">
      <select id="wifi-ssids-select" class="selectpicker" style="width:200px">
      </select>

      <p>
        <input type="password" id="wifi-password" 
         onkeydown="if (event.keyCode==13) document.getElementById('join-wifi-button').click()"
         placeholder='Wifi Password' style="width:200px">
        <input type="checkbox" onclick="makePasswordVisible()"> Show Password
      </p>

      <a class="badge badge-secondary" data-toggle="collapse" id="join-wifi-button"
        style="width:200px" href="" role="button" onclick="joinWifi();">
        Join Wifi</a>
      </br>

      <p>
        If you have trouble connecting to your wireless network, please try the: <a href="/connect/advanced">Advanced wireless network configuration</a> 
      </p>
    </div>


  </div>
  </div>

</div>
</body>
</html>
{% endblock %}
